package com.wei.czz.framework.blog.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import com.wei.czz.common.annotation.Auth;
import com.wei.czz.common.tool.Result;
import com.wei.czz.framework.blog.service.BlogContentService;
import com.wei.czz.framework.blog.service.BlogTagService;
import com.wei.czz.framework.common.service.AsyncService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2021-03-15 10:31:23
 * className: BlogContentController 博客正文操作请求接口类
 * version: 1.0
 * description:
 */
@RestController
@RequestMapping("blog/blog-content")
@AllArgsConstructor
public class BlogContentController {

    private static final Logger log = LoggerFactory.getLogger(BlogContentController.class);

    private final BlogContentService blogContentService;

    private final BlogTagService blogTagService;

    private final AsyncService asyncService;

    /**
     * 根据博客id，获取博客正文信息接口
     *
     * 调用方：
     *  1、浏览器-后台管理页面-博客审核页面-博客正文弹出框中调用
     * @param blogId 博客id
     */
    @GetMapping("/info")
    @Auth(permit = "blog:check:info")
    public Result<Map<String, Object>> getBlogContent(@RequestParam("blogId") Long blogId) {
        log.info("开始根据博客id查询博客正文业务。blogId={}", blogId);

        Future<List<String>> future = asyncService.submit(() -> {
            log.info("开始异步查询博客关联的标签名字列表业务");

            List<String> tagNameList = blogTagService.findNameList(blogId);

            log.info("异步查询博客关联的标签名字列表业务结束");

            return tagNameList;
        });

        // 主业务
        String content = blogContentService.getBlogContentById(blogId);

        List<String> tagNames;
        try {
            tagNames = future.get();
            log.info("异步查询博客关联的标签名字列表业务结束");
        } catch (InterruptedException | ExecutionException e) {
            log.error("异步查询博客关联的标签名字列表业务异常，请务必及时处理");
            return Result.fail("获取博客信息失败，请联系管理员处理。");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("content", content); data.put("tagNames", tagNames);

        log.info("根据博客id查询博客正文业务结束");
        return Result.success(data);
    }

}
